using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;

namespace MalRec.Base.ExceptionHandling
{
    public class ExceptionPolicyConfigHandler : IConfigurationSectionHandler
    {
        #region private members

        #endregion private members

        #region public members

        #endregion public members

        #region constructors

        #endregion constructors

        #region private methods

        #endregion private methods

        #region protected methods

        #endregion protected methods

        #region public methods

        #endregion public methods

        #region IConfigurationSectionHandler Member

        /// <summary>
        /// Creates an config section handler
        /// </summary>
        /// <param name="parent">the config parent</param>
        /// <param name="configContext">the config context</param>
        /// <param name="section">the xml node section</param>
        /// <returns>a list of exception policies</returns>
        public object Create(object parent, object configContext, XmlNode section)
        {
            List<ExceptionPolicy> policies = new List<ExceptionPolicy>();

            XmlNodeList policyNodes = section.SelectNodes("ExceptionPolicy");
            if (policyNodes != null)
            {
                foreach (XmlNode policyNode in policyNodes)
                {
                    if (policyNode.SelectSingleNode("Name") != null &&
                        !String.IsNullOrEmpty(policyNode.SelectSingleNode("Name").InnerText))
                    {
                        string name = policyNode.SelectSingleNode("Name").InnerText.ToLower();
                        bool rethrow = false;
                        if (policyNode.SelectSingleNode("Rethrow") != null)
                        {
                            rethrow = Convert.ToBoolean(policyNode.SelectSingleNode("Rethrow").InnerText);
                        }

                        string description = String.Empty;
                        if (policyNode.SelectSingleNode("Description") != null)
                        {
                            description = policyNode.SelectSingleNode("Description").InnerText;
                        }

                        int propagation = 0;
                        if (policyNode.SelectSingleNode("Propagation") != null)
                        {
                            propagation = Convert.ToInt32(policyNode.SelectSingleNode("Propagation").InnerText);
                        }

                        ExceptionPolicy policy = new ExceptionPolicy(name, description, propagation, rethrow);
                        policies.Add(policy);
                    }
                }
            }

            return policies;
        }

        #endregion IConfigurationSectionHandler Member
    }
}